// ========== 核心类型 ==========
interface ExtensionConfig {
  name: string;
  addCommands?(): Record<string, Function>;
  onCreate?(): void;
  onDestroy?(): void;
}

// ========== Extension 类 ==========
export class Extension {
  name: string;
  private config: ExtensionConfig;

  constructor(config: ExtensionConfig) {
    this.name = config.name;
    this.config = config;
  }

  onCreate() {
    this.config.onCreate?.();
  }
  onDestroy() {
    this.config.onDestroy?.();
  }

  getCommands() {
    return this.config.addCommands?.() ?? {};
  }
}

// ========== Editor 核心类 ==========
export class Editor {
  private extensions: Extension[] = [];
  private commands: Record<string, Function> = {};
  private doc: any[] = []; // 核心功能：存储文档

  constructor(options: { extensions?: Extension[]; content?: any[] } = {}) {
    if (options.extensions) {
      for (const ext of options.extensions) {
        this.registerExtension(ext);
      }
    }
    this.doc = options.content || [];
  }

  // 核心功能：管理文档
  setContent(content: any[]) {
    this.doc = content;
  }

  getContent() {
    return this.doc;
  }

  render() {
    // 核心渲染功能：把 doc 简单渲染成 HTML
    return this.doc
      .map((node) => {
        if (typeof node === "string") return `<p>${node}</p>`;
        return `<p>${JSON.stringify(node)}</p>`;
      })
      .join("");
  }

  // 注册插件
  registerExtension(extension: Extension) {
    this.extensions.push(extension);
    extension.onCreate();

    Object.assign(this.commands, extension.getCommands());
  }

  get commandsAPI() {
    return this.commands;
  }

  destroy() {
    for (const ext of this.extensions) {
      ext.onDestroy();
    }
  }
}

// ========== 插件示例 ==========

// 日志扩展
const Logger = new Extension({
  name: "logger",
  onCreate() {
    console.log("📝 Logger 扩展已加载");
  },
  addCommands() {
    return {
      log: (msg: string) => console.log(`[Logger]: ${msg}`),
    };
  },
  onDestroy() {
    console.log("📝 Logger 扩展已销毁");
  },
});

// 计分扩展
const Score = new Extension({
  name: "score",
  onCreate() {
    console.log("🏆 Score 扩展已加载");
  },
  addCommands() {
    let score = 0;
    return {
      addScore: (val: number) => {
        score += val;
        console.log(`当前分数: ${score}`);
      },
    };
  },
});

// ========== 使用示例 ==========
const editor = new Editor({
  extensions: [Logger, Score],
  content: ["初始文档段落"], // 核心功能内容
});

// 使用核心功能：获取和渲染文档
console.log("文档渲染结果:");
console.log(editor.render());

// 使用插件命令
editor.commandsAPI.log("编辑计分开始");
editor.commandsAPI.addScore(10);
editor.commandsAPI.addScore(20);

// 修改文档内容
editor.setContent(["修改后的段落内容"]);
console.log("修改后文档渲染结果:");
console.log(editor.render());

// 销毁插件
editor.destroy();
